<template>
	<!-- 对话框（建筑详情） -->
	<el-dialog v-model="visibleInner" append-to-body center destroy-on-close draggable width="75%" @close="dialogClosed">
		<el-descriptions v-loading="loading" :column="5" :title="_building.buildingName" border>
			<template #extra>
				<div style="margin-top: 10px">
					相关配方：
					<el-button-group size="small">
						<el-button @click="toRecipe('asProduct')">作为产物</el-button>
						<el-button :disabled="!productionBuildingOptionList.some(buildingItem => buildingItem.id === _building.id)"
						           @click="toRecipe('asProductionBuilding')">
							作为生产建筑
						</el-button>
					</el-button-group>
				</div>
			</template>
			<el-descriptions-item :span="1">
				<template #label>
					图片
				</template>
				<el-image v-if="_building.image" :src="getImage(_building.image)" fit="contain"
				          style="width: 128px; height: 128px"></el-image>
			</el-descriptions-item>
			<el-descriptions-item :span="4">
				<template #label>
					描述
				</template>
				<div class="pre-wrap">{{ _building.description }}</div>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					全类别
				</template>
				<el-tag>{{ _building.classificationNameList?.join(' / ') }}</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					需要电力
				</template>
				<el-tag :type="_building.needPower === 1 ? undefined : 'info'">{{ _building.needPower === 1 ? '是' : '否' }}</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					功率
				</template>
				<el-tag :type="(_building.power && _building.power > 1) ? undefined : 'info'">
					{{ (_building.power && _building.power > 1) ? _building.power + ' MW' : '/' }}
				</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					可超频
				</template>
				<el-tag :type="_building.overclockable === 1 ? undefined : 'info'">{{ _building.overclockable === 1 ? '是' : '否' }}</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					地貌要求
				</template>
				<el-tag v-if="!_building.landformNameList || _building.landformNameList.length === 0" type="info">/</el-tag>
				<el-tag v-for="landformName in _building.landformNameList"
				        v-else
				        :key="landformName"
				        :style="{'margin-right': _building.landformNameList.indexOf(landformName) < _building.landformNameList.length - 1 ? '5px' : undefined}">
					{{ landformName }}
				</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					传送带入口
				</template>
				<el-tag :type="(_building.beltEntrancesCount && _building.beltEntrancesCount > 0) ? undefined : 'info'">
					{{ (_building.beltEntrancesCount && _building.beltEntrancesCount > 0) ? _building.beltEntrancesCount : '/' }}
				</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					传送带出口
				</template>
				<el-tag :type="(_building.beltOutletsCount && _building.beltOutletsCount > 0) ? undefined : 'info'">
					{{ (_building.beltOutletsCount && _building.beltOutletsCount > 0) ? _building.beltOutletsCount : '/' }}
				</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					管道入口
				</template>
				<el-tag :type="(_building.pipeInletsCount && _building.pipeInletsCount > 0) ? undefined : 'info'">
					{{ (_building.pipeInletsCount) ? _building.pipeInletsCount : '/' }}
				</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					管道出口
				</template>
				<el-tag :type="(_building.pipeOutletsCount && _building.pipeOutletsCount > 0) ? undefined : 'info'">
					{{ (_building.pipeOutletsCount && _building.pipeOutletsCount > 0) ? _building.pipeOutletsCount : '/' }}
				</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					无区别管道口
				</template>
				<el-tag :type="(_building.pipeHoleCount && _building.pipeHoleCount > 0) ? undefined : 'info'">
					{{ (_building.pipeHoleCount) ? _building.pipeHoleCount : '/' }}
				</el-tag>
			</el-descriptions-item>
		</el-descriptions>
	</el-dialog>
</template>

<script lang="ts" setup>

import {computed, reactive, ref, watch} from 'vue'
import {getImage} from '@/utils/commonUtil'
import router from '@/router'
import {useRoute} from 'vue-router'
import {getAllProductionBuildingApi} from '@/api/gameData/recipe.api'
import {useRouteParamsStore} from '@/stores/modules/routeParams.store'
import {cloneDeep} from 'lodash-es'
import {CACHE_DURATION} from '@/utils/constantsUtil'
import {useUserCacheStore} from '@/stores/modules/userInfo.store'
import {getBuildingDetailByIdApi} from '@/api/gameData/building.api'

const route = useRoute()
const routeParamsStore = useRouteParamsStore()
const userCacheStore = useUserCacheStore()

interface Props {
	building?: BuildingDetailVo
	buildingId?: number
	visible?: boolean
}

const props = withDefaults(defineProps<Props>(), {
	visible: false
})

const emits = defineEmits<{
	(e: 'update:visible', value: boolean): void
	(e: 'close'): void
	(e: 'searchRecipe', params?: SearchRecipeRequest): void
}>()

const productionBuildingOptionList = ref<GBuilding[]>([])

const visibleInner = computed({
	get() {
		return props.visible
	},
	set(val) {
		emits('update:visible', val)
	}
})

const loading = computed(() => productionBuildingLoading.value || buildingInfoLoading.value)
const productionBuildingLoading = ref(false)
const buildingInfoLoading = ref(false)

const _building = reactive<BuildingDetailVo>({
	id: undefined,
	buildingName: undefined,
	description: undefined,
	beltEntrancesCount: undefined,
	beltOutletsCount: undefined,
	pipeInletsCount: undefined,
	pipeOutletsCount: undefined,
	pipeHoleCount: undefined,
	needPower: undefined,
	power: undefined,
	overclockable: undefined,
	isVehicle: undefined,
	isRequireLandform: undefined,
	image: undefined,
	classificationId: undefined,
	sort: undefined,
	customSort: undefined,
	classificationNameList: undefined,
	landformNameList: undefined,
	operator: undefined,
	createTime: undefined,
	updateTime: undefined
})

const resetBuildingInfo = () => {
	for (const key in _building) {
		_building[<keyof BuildingDetailVo>key] = undefined
	}
}

const dialogClosed = () => {
	emits('close')
}

const toRecipe = (type: 'asProduct' | 'asProductionBuilding') => {
	visibleInner.value = false
	switch (type) {
		case 'asProduct':
			emits('searchRecipe', {
				productItemId: undefined,
				productBuildingId: _building.id,
				materialItemId: undefined,
				productionBuildingId: undefined
			})
			if (route.name !== 'Recipe') {
				routeParamsStore.setParams({
					productBuildingId: _building.id
				}, 'Recipe')
				router.push({name: 'Recipe'})
			}
			break
		case 'asProductionBuilding':
			emits('searchRecipe', {
				productItemId: undefined,
				productBuildingId: undefined,
				materialItemId: undefined,
				productionBuildingId: _building.id
			})
			if (route.name !== 'Recipe') {
				routeParamsStore.setParams({
					productionBuildingId: _building.id
				}, 'Recipe')
				router.push({name: 'Recipe'})
			}
			break
	}
}

const initProductionBuilding = () => {
	// 优先从缓存中获取
	const productionBuildingCache = userCacheStore.productionBuildingCache
	if (productionBuildingCache && productionBuildingCache.expire && productionBuildingCache.expire > Date.now()) {
		productionBuildingOptionList.value = productionBuildingCache.data!
	} else {
		productionBuildingLoading.value = true
		getAllProductionBuildingApi().then(response => {
			productionBuildingOptionList.value = response.data
			userCacheStore.productionBuildingCache.data = cloneDeep(response.data)
			userCacheStore.productionBuildingCache.expire = Date.now() + CACHE_DURATION.PRODUCTION_BUILDING
		}).finally(() => {
			productionBuildingLoading.value = false
		})
	}
}

watch([() => props.building, () => props.buildingId], val => {
	resetBuildingInfo()
	const [building, buildingId] = val
	// 优先使用传入的props.building，如果props.building为空，则使用props.buildingId查询建筑信息
	if (building) {
		Object.assign(_building, building)
		// 如果给了建筑id，缓存中没有则加入，有则覆盖
		if (building.id && building.id > 0) {
			const itemCacheElement = userCacheStore.buildingCache[building.id]
			if (itemCacheElement && itemCacheElement.expire && itemCacheElement.expire > Date.now()) {
				Object.assign(itemCacheElement, building)
			} else {
				userCacheStore.buildingCache[building.id] = cloneDeep(building)
				userCacheStore.buildingCache[building.id].expire = Date.now() + CACHE_DURATION.ITEM
			}
		}
		// 初始化生产建筑列表
		initProductionBuilding()
	} else if (buildingId && buildingId > 0) {
		// 先尝试从缓存中获取建筑信息
		const itemCacheElement = userCacheStore.buildingCache[buildingId]
		if (itemCacheElement && itemCacheElement.expire && itemCacheElement.expire > Date.now()) {
			Object.assign(_building, itemCacheElement)
		}
		// 如果缓存中没有，则查询建筑信息，并加入缓存
		else {
			buildingInfoLoading.value = true
			getBuildingDetailByIdApi(buildingId).then(response => {
				Object.assign(_building, response.data)
				userCacheStore.buildingCache[buildingId] = response.data
				userCacheStore.buildingCache[buildingId].expire = Date.now() + CACHE_DURATION.BUILDING
			}).finally(() => {
				buildingInfoLoading.value = false
			})
		}
		// 初始化生产建筑列表
		initProductionBuilding()
	}
})

</script>

<style lang="scss" scoped>
</style>
